package com.lb.shopguide.ui.fragment.boss;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.event.boss.ChargeOutEvent;
import com.lb.shopguide.http.method.ApiMethodBoss;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.SimpleObserverOtherListener;
import com.lb.shopguide.ui.view.ClearTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.BizUtil;
import com.lb.shopguide.util.lb.MathDecimalUtil;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * Created by kang on 2017/12/26.
 * 提现页面
 */

public class FragmentChargeOutMoney extends BaseCommonFragment {
    @BindView(R.id.ctb)
    ClearTitleBar ctb;
    @BindView(R.id.et_charge_money)
    EditText etMoney;
    @BindView(R.id.tv_charge_account)
    TextView tvAccount;
    @BindView(R.id.tv_charge_out)
    TextView tvChargeOut;
    @BindView(R.id.tv_service_charge)
    TextView tvServiceCharge;

    private String account;
    private String withdrawCashPoundage;
    private String accountBalance;
    private Double poundage;
    private boolean chargeClickable = false;

    public static FragmentChargeOutMoney newInstance(String account) {
        FragmentChargeOutMoney fragmentChargeOutMoney = new FragmentChargeOutMoney();
        Bundle bundle = new Bundle();
        bundle.putString(AppConstant.RECEIVE_ACCOUNT, account);
        fragmentChargeOutMoney.setArguments(bundle);
        return fragmentChargeOutMoney;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_boss_charge_out;
    }

    @Override
    public void initData() {
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.RECEIVE_ACCOUNT)) {
            account = bundle.getString(AppConstant.RECEIVE_ACCOUNT);
        }
        getWithdrawCashInfo();
    }

    @Override
    public void initView() {
        ctb.setTvTitle("提现");
        ctb.setLeftImageSrc(R.drawable.iv_back);
        ctb.setOnLeftImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pop();
            }
        });

        bindData();
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {

    }

    @Override
    public void requestError(String error) {

    }

    private void bindData() {
        if (etMoney != null) {
            KeyboardUtils.showSoftInput(etMoney);
        }
        tvAccount.setText(account + " " + "支付宝账户");

        etMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    setChargeEnable(false);
                    bindBalance();
                    return;
                }
                String content = "";
                String money = s.toString();
                String poundageMoney = MathDecimalUtil.formatDouble(Double.parseDouble(money) * poundage);
                money = MathDecimalUtil.formatDouble(Double.parseDouble(money) * (1 + poundage));
                SpannableString mSp = null;
                if (Double.parseDouble(money) > Double.parseDouble(accountBalance)) {//超出余额
                    content = "应扣除金额超过账户余额";
                    mSp = new SpannableString(content);
                    mSp.setSpan(new ForegroundColorSpan(Color.rgb(255, 86, 57)), 0, content.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //设置前景色为洋红色
                    setChargeEnable(false);
                } else {//正常取现
                    content = "实际扣除余额￥" + money + " (￥" + poundageMoney + "手续费)";
                    mSp = new SpannableString(content);
                    mSp.setSpan(new ForegroundColorSpan(Color.rgb(255, 86, 57)), content.indexOf("("), content.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //设置前景色为洋红色
                    setChargeEnable(true);
                }
                if (mSp != null) {
                    tvServiceCharge.setText(mSp);
                }

            }
        });
    }

    private void setChargeEnable(boolean flag) {
        chargeClickable = flag;
        if (flag) {
            tvChargeOut.setBackgroundResource(R.drawable.bg_round_corner_red_6dp);
        } else {
            tvChargeOut.setBackgroundResource(R.drawable.bg_round_corner_red_6dp_unable);
        }
    }

    private void bindBalance() {
        poundage = Double.parseDouble(withdrawCashPoundage);
        String content = "账户余额￥" + accountBalance;
        tvServiceCharge.setText(content);
        SpannableString mSp = new SpannableString(content);
        mSp.setSpan(new ForegroundColorSpan(Color.rgb(22, 105, 231)), content.indexOf("￥") + 1, content.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //设置前景色为洋红色
        tvServiceCharge.setText(mSp);
    }

    private void getWithdrawCashInfo() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JSONObject jsonObject = JsonUtil.getJsonObjectFromMap(response.getReturnContent());
                    try {
                        withdrawCashPoundage = jsonObject.getString("withdrawCashPoundage");
                        accountBalance = jsonObject.getString("accountBalance");
                        bindBalance();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        ApiMethodBoss.getWithdrawCashInfo(new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestChargeOutMoney() {
        RequestBody body = getRequestBody();
        if (body == null) {
            return;
        }
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {
            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == (ResponseCode.RESPONSE_SUCCESS)) {
                    ToastUtils.showShort("申请成功");
                    EventBus.getDefault().post(new ChargeOutEvent());
                    pop();
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
            }
        };
        SimpleObserverOtherListener errorListener = new SimpleObserverOtherListener() {
            @Override
            public void onSessionOutOfDate() {

            }

            @Override
            public void onError(String error) {
                ToastUtils.showShort("提现失败" + error);

            }
        };
        ApiMethodBoss.chargeInOutMoney(new SimpleLbObserver(listener, errorListener), body, this, FragmentEvent.DESTROY_VIEW);
    }

    private RequestBody getRequestBody() {
        String money = etMoney.getText().toString();
        HashMap hashMap = new HashMap();
        hashMap.put("moneyAmount", money);
        return BizUtil.getBodyFromMap(hashMap);
    }

    @Override
    public String getPageTag() {
        return FragmentChargeOutMoney.class.getName();
    }

    @OnClick()
    void chargeOut() {
        if (chargeClickable) {


            String money = etMoney.getText().toString();
            if (TextUtils.isEmpty(money)) {
                ToastUtils.showShort("请输入提现金额");
                return;
            }
            float fMoney = Float.parseFloat(money);
            if (fMoney == 0f) {
                ToastUtils.showShort("请输入正确的提现金额");
                return;
            }
            sendRequestChargeOutMoney();
        }
    }
}
